package com.tangyee.home_exercise_diet;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.tangyee.home_blood_center.utils.DateUtil;
import com.tangyee.home_blood_center.utils.DensityUtils;
import com.tangyee.R;
import com.tangyee.home_blood_center.utils.DateUtil;
import com.tangyee.home_blood_center.utils.DensityUtils;
import com.tangyee.home_exercise_diet.activities.About;
import com.tangyee.home_exercise_diet.activities.AddFoodOrExerciseActivity;
import com.tangyee.home_exercise_diet.activities.EditFoodOrExerciseList;
import com.tangyee.home_exercise_diet.beans.FoodOrExercise;
import com.tangyee.home_exercise_diet.beans.TypeEnum;
import com.tangyee.home_exercise_diet.dao.FoodOrExerciseHolder;
import com.tangyee.home_exercise_diet.view.CircleView;
import com.tangyee.home_exercise_step.StepActivity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

public class ExerciseAndDietActivity extends AppCompatActivity {

    // ScrollView中的LinearLayout
    private LinearLayout mLinearLayout;

    // 存放当天所有的饮食/运动记录
    private List<FoodOrExercise> total;

    // 存放早餐 早上加餐 .... 的记录的list
    private List<FoodOrExercise> breakfastList;
    private List<FoodOrExercise> extraBreakfastList;
    private List<FoodOrExercise> lunchList;
    private List<FoodOrExercise> extraLunchList;
    private List<FoodOrExercise> dinnerList;
    private List<FoodOrExercise> extraDinnerList;
    private List<FoodOrExercise> exerciseList;

    // 早餐 早上加餐...和运动 的 卡路里数
    private double breakfastCalorie, extraBreakfastCalorie,lunchCalorie,extraLunchCalorie,dinnerCalorie,extraDinnerCalorie,exerciseCalorie;

    // 存放所有添加进ScrollView的子View
    private List<View> views = new ArrayList<>();

    // 界面下面一排选择按钮
    private Button breakfast, lunch, dinner, extraMeal, exercise;

    // 日期
    private Date date;
    private int mYear, mMonth, mDay;
    // 打开弹窗的标记，主要用于保证每次打开的日期弹窗都是新new的
    private int dialog_sign = 1;

    // 标题栏的返回箭头 和 日期 TextView
    private ImageView back;
    private TextView dateTv;

    // 标题栏日期旁边的两个小按钮
    private ImageView left;
    private ImageView right;

    //标题栏计步功能
    private ImageView stepView;

    // 加餐弹窗
    private AlertView mAlertView;

    // 摄入值 运动消耗值 预算
    private int ingestion, consume, budget = 1621;
    private TextView ingestionTv, consumeTv, numberTv, budgetTv, eat;

    // 圆形view
    private CircleView mCircleView;

    // 没有数据时显示的textView
    private TextView emptyView;

    // 运动/饮食信息的标题（就是最绿的那部分，不是标题栏）
    private LinearLayout titleLinearLayout;

    private final static int REQUESTCODE = 1; // start About Activity的返回的结果码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.exercise_and_diet_activity_main);

        this.dateTv = findViewById(R.id.center_text);
        this.date = new Date();
        // 更新日期数据
        updateDate();

        this.back = findViewById(R.id.back);
        // 返回箭头点击事件
        back.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        // 标题日期点击打开日期选择弹窗事件
        dateTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog(dialog_sign++);  //弹出dialog
            }
        });

        left = findViewById(R.id.left_img);
        // 标题日期左边的小箭头
        left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                date = DateUtil.getPreDate(date, 1);
                updateDate();
                updateUI();
            }
        });
        right = findViewById(R.id.right_img);
        // 标题日期右边的小箭头
        right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Date d = DateUtil.getPreDate(date, -1);
                if (new Date().getTime() >= d.getTime()) {
                    date = d;
                    updateDate();
                    updateUI();
                }
            }
        });

        stepView = findViewById(R.id.step);
        stepView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ExerciseAndDietActivity.this, StepActivity.class);
                startActivity(intent);
            }
        });

        this.mLinearLayout = findViewById(R.id.scrollview_linearlayout);
        this.titleLinearLayout = findViewById(R.id.title_linearlayout);
        // 运动/饮食信息部分的点击事件
        titleLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ExerciseAndDietActivity.this, About.class);
                intent.putExtra("budget", budget);
                startActivityForResult(intent, REQUESTCODE);
            }
        });

        this.ingestionTv = findViewById(R.id.ingestion);
        this.consumeTv = findViewById(R.id.consume);
        this.numberTv = findViewById(R.id.number_text);
        this.budgetTv = findViewById(R.id.budget);
        this.eat = findViewById(R.id.eat);
        this.mCircleView = findViewById(R.id.circle_view);
        this.emptyView = findViewById(R.id.empty_view);

        // 更新数据与界面
        updateUI();


        // 最底下一排按钮的点击事件
        this.breakfast = findViewById(R.id.breakfast_btn);
        breakfast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startAddFoodActivity(TypeEnum.BREAKFAST.name());
            }
        });

        this.lunch = findViewById(R.id.lunch_btn);
        lunch.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                startAddFoodActivity(TypeEnum.LUNCH.name());
            }
        });

        this.dinner = findViewById(R.id.dinner_btn);
        dinner.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                startAddFoodActivity(TypeEnum.DINNER.name());
            }
        });

        this.extraMeal = findViewById(R.id.extra_meal_btn);
        extraMeal.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {

                mAlertView = new AlertView("加餐", null, "取消", null,
                        new String[]{
                                "早上加餐",
                                "中午加餐",
                                "晚上加餐"
                        },
                        ExerciseAndDietActivity.this, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == -1){
                            return;
                        }
                        if (position == 0)
                            startAddFoodActivity(TypeEnum.EXTRA_BREAKFAST.name());
                        else if (position == 1)
                            startAddFoodActivity(TypeEnum.EXTRA_LUNDH.name());
                        else if (position == 2)
                            startAddFoodActivity(TypeEnum.EXTRA_DINNER.name());
                    }
                }).setCancelable(true);
                mAlertView.show();

             }
        });

        this.exercise = findViewById(R.id.exercise_btn);
        exercise.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                startAddFoodActivity(TypeEnum.EXERCISE.name());
            }
        });

    }

    /**
     * 更新日期数据
     */
    private void updateDate() {
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        mYear = ca.get(Calendar.YEAR);
        mMonth = ca.get(Calendar.MONTH);
        mDay = ca.get(Calendar.DAY_OF_MONTH);
        dateTv.setText((mMonth+1)+"月"+mDay+"日");
    }

    /**
     * 重写返回键事件
     */
    @Override
    public void onBackPressed() {
        // 如果弹窗是显示的，则让其消失，不销毁当前Activity
        if (mAlertView == null || !mAlertView.isShowing())
            super.onBackPressed();
        else
            mAlertView.dismiss();
    }

    // showDialog()方法会自动调用这个方法，重写它，使其创建我们需要的日期弹窗
    @Override
    protected Dialog onCreateDialog(int id) {
        //弹出dialogDataPicker
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, mdateListener, mYear, mMonth, mDay);
        datePickerDialog.getDatePicker().setMaxDate(new Date().getTime());
        datePickerDialog.getDatePicker();
        return datePickerDialog;
    }

    /**
     * 日期弹窗DatePickerDialog的回调
     */
    private DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int day) {
            Date d = new GregorianCalendar(year, month, day, 0, 0, 0).getTime();
            if (new Date().getTime() >= d.getTime()) {
                date = d;
                mYear = year;
                mMonth = month;
                mDay = day;
                dateTv.setText((month+1)+"月"+day+"日");
                updateUI();
            }
        }
    };

    /**
     * 更新界面和数据
     */
    private void updateUI() {
        this.total = FoodOrExerciseHolder.get(getApplicationContext()).getListByDate(date);
        this.breakfastList = new ArrayList<>();
        this.extraBreakfastList = new ArrayList<>();
        this.lunchList = new ArrayList<>();
        this.extraLunchList = new ArrayList<>();
        this.dinnerList = new ArrayList<>();
        this.extraDinnerList = new ArrayList<>();
        this.exerciseList = new ArrayList<>();

        // 分析所有的记录
        analyzeList();

        for (View view : views){
            mLinearLayout.removeView(view);
        }
        views.clear();

        // 单独解析每一种记录的List
        analyzeDiet(breakfastList, TypeEnum.BREAKFAST);
        analyzeDiet(extraBreakfastList, TypeEnum.EXTRA_BREAKFAST);
        analyzeDiet(lunchList, TypeEnum.LUNCH);
        analyzeDiet(extraLunchList, TypeEnum.EXTRA_LUNDH);
        analyzeDiet(dinnerList, TypeEnum.DINNER);
        analyzeDiet(extraDinnerList, TypeEnum.EXTRA_DINNER);
        analyzeDiet(exerciseList, TypeEnum.EXERCISE);

        ingestion = (int) (breakfastCalorie + extraBreakfastCalorie + lunchCalorie + extraLunchCalorie + dinnerCalorie + extraDinnerCalorie);
        consume = (int) exerciseCalorie;

        ingestionTv.setText("摄入\n\n"+ingestion);
        consumeTv.setText("运动\n\n" + consume);
        budgetTv.setText("预算 "+budget);

        // 下面是 还可以吃多少 的逻辑
        int a = ingestion - consume;
        if (a <= 0){
            mCircleView.setDate(0, budget);
            numberTv.setText((budget - a) + "");
        }
        if (a > 0 && a <= budget){
            mCircleView.setDate(budget - a, budget);
            numberTv.setText((budget - a)+"");
        }
        if (a > 0 && a > budget){
            mCircleView.setDate(budget, budget);
            eat.setText("多吃了");
            numberTv.setText((a - budget) + "");
        } else {
            eat.setText("还可以吃");
        }

        // 判断是否有数据，没有则显示emptyView
        if (emptyView != null && views.size() == 0 && consume == 0 && ingestion == 0){
            emptyView.setVisibility(View.VISIBLE);
        } else if (emptyView != null){
            emptyView.setVisibility(View.GONE);
        }
    }

    /**
     * 分析所有的记录
     */
    private void analyzeList() {
        breakfastCalorie = 0;
        extraBreakfastCalorie = 0;
        lunchCalorie = 0;
        extraLunchCalorie = 0;
        dinnerCalorie = 0;
        extraDinnerCalorie = 0;
        exerciseCalorie = 0;

        for (int i = 0; i < total.size(); i ++){
            FoodOrExercise f = total.get(i);
            if (f.getType().equals(TypeEnum.BREAKFAST)){
                this.breakfastList.add(f);
                breakfastCalorie += f.getAmount()/100*f.getPerUnitCalorie();
            } else if (f.getType().equals(TypeEnum.LUNCH)){
                this.lunchList.add(f);
                lunchCalorie += f.getAmount()/100*f.getPerUnitCalorie();
            } else if (f.getType().equals(TypeEnum.DINNER)){
                this.dinnerList.add(f);
                dinnerCalorie += f.getAmount()/100*f.getPerUnitCalorie();
            } else if (f.getType().equals(TypeEnum.EXERCISE)){
                this.exerciseList.add(f);
                exerciseCalorie += f.getAmount()/60*f.getPerUnitCalorie();
            } else if (f.getType().equals(TypeEnum.EXTRA_BREAKFAST)){
                this.extraBreakfastList.add(f);
                extraBreakfastCalorie += f.getAmount()/100*f.getPerUnitCalorie();
            } else if (f.getType().equals(TypeEnum.EXTRA_LUNDH)){
                this.extraLunchList.add(f);
                extraLunchCalorie += f.getAmount()/100*f.getPerUnitCalorie();
            } else if (f.getType().equals(TypeEnum.EXTRA_DINNER)){
                this.extraDinnerList.add(f);
                extraDinnerCalorie += f.getAmount()/100*f.getPerUnitCalorie();
            }
        }
    }

    /**
     * 打开添加食物/运动的Activity
     * @param type
     */
    private void startAddFoodActivity(String type) {
        Intent intent = new Intent(ExerciseAndDietActivity.this, AddFoodOrExerciseActivity.class);
        intent.putExtra(AddFoodOrExerciseActivity.DATE, DateUtil.date2Str(date, "yyyy-MM-dd"));
        intent.putExtra(AddFoodOrExerciseActivity.TYPE, type);
        startActivity(intent);
    }

    /**
     * 解析每一种记录的List
     * @param list
     * @param typeEnum
     */
    private void analyzeDiet(final List<FoodOrExercise> list, final TypeEnum typeEnum){
        if (list == null || list.size() <= 0)
            return;
        String type = list.get(0).getType().getTypeName();
        LinearLayout linearLayout = getLayoutInflater().inflate(R.layout.exercise_and_diet_scrollview_item_title, null).findViewById(R.id.item_breakfast_lunch_dinner_title);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, DensityUtils.dp2px(this, 50) + DensityUtils.dp2px(this, 60) * list.size());
        layoutParams.setMargins(0, DensityUtils.dp2px(this, 8), 0, 0);
        mLinearLayout.addView(linearLayout, layoutParams);
        views.add(linearLayout);
        ((TextView)linearLayout.findViewById(R.id.item_title)).setText(type);
        ((TextView)linearLayout.findViewById(R.id.item_calorie)).setText(String.format("%.2f千卡", getCalorieByType(type)));

        for (int i = 0; i < list.size(); i ++){
            FoodOrExercise foodOrExercise = list.get(i);
            LinearLayout itemView = getLayoutInflater().inflate(R.layout.exercise_and_diet_scrollview_item, null).findViewById(R.id.item_diet);
            adapterDiet(itemView, foodOrExercise);
            LinearLayout.LayoutParams itemLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, DensityUtils.dp2px(this, 60));
            if (i == 0){
                itemView.setBackgroundResource(R.drawable.top_line_shape);
            }
            if (i != list.size() - 1){
                itemView.findViewById(R.id.item_content).setBackgroundResource(R.drawable.bottom_line_shape);
            } else {
                itemLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, DensityUtils.dp2px(this, 60) - 1);
            }
            linearLayout.addView(itemView, itemLayoutParams);
        }

        // 设置点击事件
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ExerciseAndDietActivity.this, EditFoodOrExerciseList.class);
                intent.putExtra(EditFoodOrExerciseList.TYPE, typeEnum.name());
                intent.putExtra(EditFoodOrExerciseList.DATE, DateUtil.date2Str(date, "yyyy-MM-dd"));
                startActivity(intent);
            }
        });

    }

    /**
     * 计算每一种记录的卡路里
     * @param type
     * @return
     */
    private double getCalorieByType(String type){
        if ("早餐".equals(type))
            return breakfastCalorie;
        else if ("午餐".equals(type))
            return lunchCalorie;
        else if ("晚餐".equals(type))
            return dinnerCalorie;
        else if ("早上加餐".equals(type))
            return extraBreakfastCalorie;
        else if ("中午加餐".equals(type))
            return extraLunchCalorie;
        else if ("晚上加餐".equals(type))
            return extraDinnerCalorie;
        else
            return exerciseCalorie;
    }

    /**
     * 将一条条记录适配到每一个ItemView上
     * @param itemView
     * @param foodOrExercise
     */
    private void adapterDiet(View itemView, FoodOrExercise foodOrExercise){
        ImageView item_img = itemView.findViewById(R.id.item_img);
        TextView food_title = itemView.findViewById(R.id.food_title);
        TextView food_weight = itemView.findViewById(R.id.food_weight);
        TextView food_calorie = itemView.findViewById(R.id.food_calorie);

        int n = 100;
        if (foodOrExercise.getType().equals(TypeEnum.EXERCISE)){
            n = 60;
        }

        String unit = foodOrExercise.getUnit();
        unit = unit.substring(unit.lastIndexOf('0')+1);

        item_img.setImageResource(foodOrExercise.getImg());
        food_title.setText(foodOrExercise.getName());
        food_weight.setText(String.format("%.2f", foodOrExercise.getAmount()) + unit);
        food_calorie.setText(String.format("%.2f", foodOrExercise.getPerUnitCalorie()*1.0*foodOrExercise.getAmount()/n)+"千卡");
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateUI();
    }

    /**
     * 启动 About Acitvity后的回调（返回数据的处理）
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2){
            if (requestCode == REQUESTCODE){
                budget = data.getIntExtra("budget", budget);
                updateUI();
            }
        }
    }
}
